const util = require("../../utils/util.js");
var app = getApp();
var that;

Page({
  data: {
    // 位置信息
    location: "",
    // 可配送城市  
    distributCitys: [],
    changeLocation: false,
    scrollTop: 0,
    // 左侧菜单列表
    leftClassesMenuList: [{
      id: 1,
      name: "A"
    }, {
      id: 2,
      name: "B"
    }, {
      id: 3,
      name: "C"
    }, {
      id: 4,
      name: "D"
    }],
    // 左侧菜单选中item
    selectedLeftMenuItem: 1,
    // 商品列表
    productList: [{
      cateId: 1,
      cateName: "AAA",
      goodsList: [{
        goodsId: 11,
        goodsImgUrl: "http://img0.imgtn.bdimg.com/it/u=1860585386,1850494060&fm=26&gp=0.jpg",
        goodsName: "巧克力蛋糕",
        goodsPayprice: "299.00",
        goodsTotalPrice: "399.00"
      }]
    }, {
      cateId: 2,
      cateName: "BBB",
      goodsList: [{
        goodsId: 21,
        goodsImgUrl: "http://img4.imgtn.bdimg.com/it/u=3023741373,2432462321&fm=26&gp=0.jpg",
        goodsName: "红丝绒蛋糕",
        goodsPayprice: "299.00",
        goodsTotalPrice: "399.00"
      }]
    }, {
      cateId: 3,
      cateName: "CCC",
      goodsList: [{
        goodsId: 31,
        goodsImgUrl: "http://img3.imgtn.bdimg.com/it/u=896320457,2923077388&fm=26&gp=0.jpg",
        goodsName: "草莓蛋糕",
        goodsPayprice: "299.00",
        goodsTotalPrice: "399.00"
      }, {
        goodsId: 32,
        goodsImgUrl: "http://img4.imgtn.bdimg.com/it/u=2784011872,440348112&fm=26&gp=0.jpg",
        goodsName: "草莓蛋糕",
        goodsPayprice: "299.00",
        goodsTotalPrice: "399.00"
      }]
    }, {
      cateId: 4,
      cateName: "DDD",
      goodsList: [{
        goodsId: 41,
        goodsImgUrl: "http://img4.imgtn.bdimg.com/it/u=23010973,3408349461&fm=26&gp=0.jpg",
        goodsName: "多肉蛋糕",
        goodsPayprice: "299.00",
        goodsTotalPrice: "399.00"
      }]
    }],
    // 分页pageindex
    pageindex: 0,
    // 分页每页加载的个数
    pageCount: 15,
    // 是否显示加载更多
    // loadMoreTag: false,
    noMoreTag: false,
    // BD id
    shopId: null,
    longitude: "",
    latitude: "",
    shopIdFlag: false, //是否扫码进入
    cityId: 2,
    phoneStr: "",
    cartDetailFlag: false,
    cartDataSource: "",
    cartTotalSum: "",
    cartGoodsNum: "",
    goodsDetailFlag: false,
    detailInMask: "", //商品详情弹窗里的商品信息
    toView: "", //把第几个商品分类滚动到顶部
    isBottomPhone: "", //判断手机是否为没有home键的iPhone
    cartDetailContentHeight: "",
    showGetPhone: false, //是否展示获取手机号码弹窗
  },
  onShareAppMessage: function(res) {
    return {
      title: '超A蛋糕店',
      path: '/pages/index/index',
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  onShow: function() {
    that.setData({
      phoneStr: app.globalData.phone
    })
    console.log(that.data.phoneStr, "that.data.phoneStr")
    if (app.globalData.viewId) { //从创建订单页回来时，重新请求购物车内商品
      that.getCartGoods();
    }
    //设置自定义tabbar首页选中
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0 //tabBar第一个选中
      })
    }
    console.log(this.getTabBar().data.selected, "this.getTabBar().data.selected")
    console.log(app.globalData.selectedCity.name, "app.globalData.selectedCity.name");
    console.log(app.globalData.selectedCity.id, "app.globalData.selectedCity.id");
    let cityId = app.globalData.selectedCity.id;
    let location = app.globalData.selectedCity.name;
    if (that.data.changeLocation) { //从城市列表选择了其他城市
      console.log("手动变更了其他城市")
      this.setData({
        location: location,
        cityId: cityId,
        pageindex: 0,
        shopIdFlag: false,
      })
      // 获取蛋糕列表
      this.getCategoryItemsConnection();
    }
    // 获取蛋糕列表
    this.getCategoryItemsConnection();
  },
  onLoad: function(options) {
    this.$wuxToast = app.wux(this).$wuxToast;
    that = this;
    //匹配手机型号，适配购物车导航条
    if (app.globalData.isBottomPhone) {
      that.setData({
        isBottomPhone: app.globalData.isBottomPhone
      })
    }
    // 获取城市列表
    // that.getDistributCitys(); 
    if (options.shopId) { // 扫描店铺二维码进入，用shopId获取左侧菜单信息
      that.setData({
        // shopId: 156203904,
        shopId: options.shopId,
        shopIdFlag: true
      })
      app.globalData.shopId = options.shopId;
      // 获取蛋糕列表
      that.getCategoryItemsConnection();
    } else { // 直接进入小程序
      //先获取城市定位信息，再用cityId获取左侧菜单信息
      wx.getSetting({
        success(res) {
          console.log(res.authSetting, "userLocation")
          if (!res.authSetting['scope.userLocation']) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                console.log(111);
                // 用户已经同意小程序使用定位功能，后续调用 wx.getLocation 接口不会弹窗询问
                that.getLocationInfos();
              },
              fail() {
                wx.showModal({
                  title: '提示',
                  content: '您的位置信息将用于我们获您取所在城市的门店和商品，如果拒绝授权，将导致无法获取商品',
                  cancelText: "拒绝",
                  confirmText: "去授权",
                  success(res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success(res) {
                          if (res.authSetting['scope.userLocation']) {
                            that.getLocationInfos();
                          }
                        },
                        fail(res) {
                          wx.showToast({
                            title: '获取授权列表失败！',
                            icon: "none"
                          })
                        }
                      })
                    } else if (res.cancel) {
                      that.getLocationPlace();
                      console.log('用户点击取消')
                    }
                  },
                  fail() {
                    wx.showToast({
                      title: '调起授权弹窗失败，请退出重试！',
                      icon: "none"
                    })
                  }
                })
                console.log(222);
              }
            })
          } else {
            that.getLocationInfos();
          }
        },
        fail() {
          wx.showToast({
            title: '获取授权信息失败，请退出重试！',
            icon: "none"
          })
        }
      })
    }
  },
  // 获取城市定位信息
  getLocationInfos: function() {
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        var location = longitude + "," + latitude;
        var alireq = "http://restapi.amap.com/v3/geocode/regeo?output=json&location=" + location + "&key=a31d574c29ed724cc7ca9114cf88977e&radius=1000&extensions=all";
        wx.request({
          url: alireq,
          method: 'GET',
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          data: {},
          success: function(data) {
            if (data.data.status == "1") {
              var city = data.data.regeocode.addressComponent.province;
              // 去除城市末尾“市”字
              city = city.substring(0, city.length - 1);
              console.log(data.data.status, "data.data.status====");
              // 遍历城市数组     
              console.log(that.data.distributCitys, "that.data.distributCitys====")
              that.data.distributCitys.forEach((value, key) => {
                console.log(value, "distributCitys")
                // 若城市数组中存在该城市则更改所在地商品信息
                if (value.name == city) {
                  // 修改全部城市变量
                  console.log(city, "city2111")
                  that.setData({
                    location: city,
                    cityId: value.id,
                  })
                  // 修改本地存储城市变量
                  app.globalData.locationCity = value;
                  console.log(app.globalData.locationCity, "app.globalData.locationCity")
                  wx.nextTick(() => {
                    // 获取商品列表
                    that.getCategoryItemsConnection();
                  })
                }
              });
            } else {
              wx.showToast({
                title: '获取位置信息失败！',
                icon: "none"
              })
            }
          },
          fail() {
            wx.showToast({
              title: '网络请求失败！',
              icon: "none"
            })
          }
        })
      }
    })
  },
  //加载更多
  loadMore() {

  },
  // 左侧菜单栏切换事件
  selectClassesClick: function(e) {
    let dataset = e.currentTarget.dataset;
    let id = dataset.id;
    that.setData({
      selectedLeftMenuItem: id,
      toView: 'productItem' + id
    });
  },
  //监听右边商品列表滑动
  scrollProductList(e) {
    console.log(e)
    that.data.productList.forEach(item => {
      if (e.detail.scrollTop >= (item.offsetTop - 55) && e.detail.scrollTop <= (item.offsetTop - 55 + item.height)) {
        that.setData({
          selectedLeftMenuItem: item.cateId
        })
        console.log("selectedLeftMenuItem===", that.data.selectedLeftMenuItem)
      }
    })
  },
  // 绑定手机号
  bindUserPhone: function(e) {
    util.getUserPhone(e, res => {
      that.setData({
        phoneStr: res.data.data.phone,
        showGetPhone: false
      })
      app.globalData.phone = res.data.data.phone;
    });
  },
  //加减购物车内商品数量
  changeGoodsNum(e) {
    let ids = e.currentTarget.dataset.id;
    let add = e.currentTarget.dataset.add;
    if (!app.globalData.viewId) {
      that.setData({
        showGetPhone: true
      })
    } else {
      util.postRequest("/api/order/goodsCart/add", {
        goodsId: ids,
        operation: add,
      }, res => {
        that.getCartGoods();
      })
    }
  },
  getCartGoods() {
    util.getRequest("/api/order/getCartList", {}, res => {
      let data = res.data.data;
      that.setData({
        cartDataSource: data.goodsEntities,
        cartGoodsNum: data.totalNum,
        cartTotalSum: data.totalPrice
      });
      if (data.goodsEntities.length) {
        wx.createSelectorQuery().select('#cart-goods-item').boundingClientRect(rect => {
          // 30px元素cart-detail-title的高度，10像素空白，没有home键的苹果手机再加底部34像素防止误操作的告诉
          that.setData({
            cartDetailContentHeight: that.data.isBottomPhone ? rect.height * data.goodsEntities.length + 74 : rect.height * data.goodsEntities.length + 40,
          });
        }).exec()
      }
      console.log(that.data.cartDetailContentHeight, "cartDetailContentHeight")
    })
  },
  //关闭商品详情弹窗
  closeGoodsDetail() {
    that.setData({
      goodsDetailFlag: false
    })
  },
  //打开商品详情弹窗
  showGoodsDetail(e) {
    let dataset = e.currentTarget.dataset;
    if (dataset) {
      that.setData({
        detailInMask: dataset.item
      })
      console.log(that.data.detailInMask, "detailInMask")
    }
    that.setData({
      goodsDetailFlag: true
    })
  },
  //展开购物车详情
  toggleCartDetail() {
    that.setData({
      cartDetailFlag: !that.data.cartDetailFlag
    })
  },
  showCartDetail() {
    that.setData({
      cartDetailFlag: true
    })
  },
  //结算
  goToBuy() {
    wx.navigateTo({
      url: '/pages/order/createOrder/createOrder',
    })
  },
  // 返回顶部
  goTop: function(e) {
    this.setData({
      scrollTop: 0
    })
  },
  // 定位城市
  getLocationPlace: function() {
    var cityListStr = JSON.stringify(that.data.distributCitys);
    wx.navigateTo({
      url: '../location/location?cityList=' + cityListStr,
    })
  },
  //清空购物袋 
  clearCart() {
    util.getRequest("/api/order/delCart", {}, res => {
      that.getCartGoods();
    })
  },
  // 获取右侧商品列表
  getCategoryItemsConnection: function() {
    let currentUrl;
    let currentParams;
    console.log(that.data.shopIdFlag, "that.data.shopIdFlag")
    if (that.data.shopIdFlag) {
      currentUrl = "/api/homePage/getHomeListShop";
      currentParams = {
        shopId: that.data.shopId,
      }
    } else {
      currentUrl = "/api/homePage/getHomeListCity";
      currentParams = {
        cityId: that.data.cityId,
      }
    }
    //  util文件里封装了get请求
    // util.getRequest(currentUrl, currentParams, res => {
    // let dataSource = res.data.data.goods;
    // let leftClassesMenuList = res.data.data.categoryList;
    let dataSource = that.data.productList;
    let leftClassesMenuList = that.data.leftClassesMenuList;
    that.setData({
      // productList: dataSource,
      // leftClassesMenuList: leftClassesMenuList,
      selectedLeftMenuItem: leftClassesMenuList[0] ? leftClassesMenuList[0].id : '',
      toView: leftClassesMenuList[0] ? 'productItem' + leftClassesMenuList[0].id : ''
    })
    console.log("that.data.productList===", that.data.productList)
    // 给右侧商品列表循环赋值列表项的上边界坐标和高度
    that.data.productList.forEach(item => {
      console.log("item===", item);
      // 添加节点的布局位置的查询请求
      wx.createSelectorQuery().select('#productItem' + item.cateId).boundingClientRect(rect => {
        console.log(rect.top, "rect.top===")
        item.offsetTop = rect.top;
        item.height = rect.height;
      }).exec();
    });
    console.log(that.data.productList, "that.data.productList")
    if (!that.data.shopIdFlag && dataSource.length && dataSource[0].shopId) { //直接进入，shopid从接口里取
      app.globalData.shopId = dataSource[0].shopId;
    }
    if (!dataSource.length) {
      that.setData({
        noMoreTag: true,
      })
      wx.showToast({
        title: '暂无商品信息！',
        icon: 'none',
      })
    } else {
      that.setData({
        noMoreTag: false,
      })
    }
    // })
  },
  // 获取可配送城市
  getDistributCitys: function() {
    util.getRequest('/api/homePage/getCityShop', {}, res => {
      console.log("获取成功");
      console.log(that.data);
      that.setData({
        distributCitys: res.data.data
      })
      app.globalData.distributCitys = res.data.data;
    })
  },
})